package com.llkj.qingnianguoxue.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.JingXuanBookTabAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.BookTabBean;
import com.llkj.qingnianguoxue.bean.response.ResponseList;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.mine.ShopCartActivity;
import com.llkj.qingnianguoxue.util.GsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.llkj.qingnianguoxue.home.JingXuanBooksFragment.REQUEST_VIDEO_CODE;

/**
 * 范儿书籍
 */
public class JingXuanBooksActivity extends BaseActivity implements JingXuanBooksFragment.RefreshShopCountListener {
    private static final int REQUEST_CART_CODE = 7768;
    @BindView(R.id.tv_count)
    TextView tvShopCount;//购物车数量
    @BindView(R.id.lvHorizontal)
    RecyclerView lvHorizontalView;
    private JingXuanBookTabAdapter mBookTabAdapter;
    private List<BookTabBean> mTabData;
    private HashMap<Integer,JingXuanBooksFragment> mBookFragmentList;
    private int mShopCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jing_xuan_books);
        setTitle("范儿书籍", true, TITLE_TYPE_IMG, R.drawable.icon_back, true, TITLE_TYPE_IMG, R.drawable.icon_video_detail_cart);
        RelativeLayout rlTop = findViewById(R.id.rl_top);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTop,R.color.gray_bar);
        ButterKnife.bind(this);

        initView();

        mBookFragmentList = new HashMap<>();

        getBooksClassify();
    }

    private void initView() {
        lvHorizontalView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mTabData = new ArrayList<>();
        mBookTabAdapter = new JingXuanBookTabAdapter(R.layout.item_jingxuan_books_tab,mTabData);
        lvHorizontalView.setAdapter(mBookTabAdapter);

        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin){
            tvShopCount.setVisibility(View.GONE);
        }

        lvHorizontalView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mBookTabAdapter.setSelectPosition(position);
                setSelection(position);
            }
        });
    }
    private void setSelection(int index) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        JingXuanBooksFragment fragment = null;
        if(mBookFragmentList.containsKey(index)){
            fragment = mBookFragmentList.get(index);
        }
        hideFragment(fragmentTransaction);
        if (fragment == null) {
            fragment = JingXuanBooksFragment.newInstance(index,mTabData.get(index).getId());
            fragment.setShopCountListener(this);
            fragmentTransaction.add(R.id.content_layout, fragment, "tab"+index);
            mBookFragmentList.put(index,fragment);
            fragment.setShopCountListener(this);
        } else {
            fragmentTransaction.show(fragment);
        }
        fragmentTransaction.commit();
    }

    /**
     * 隐藏所有的fragment
     *
     * @param transaction
     */
    private void hideFragment(FragmentTransaction transaction) {
       for(int i=0;i<mBookFragmentList.size();i++){
           Fragment fragment =  mBookFragmentList.get(i);
           if (fragment != null) {
               transaction.hide(fragment);
           }

       }
    }
    @Override
    protected void rightDoWhat() {
        super.rightDoWhat();
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        startActivityForResult(ShopCartActivity.class, new Bundle(), REQUEST_CART_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == REQUEST_CART_CODE){//购物车
            if(data != null && (data.hasExtra("result") || data.hasExtra("del"))){//购物车中操作了，购买，删除
//                onRefresh();
            }
        }else if(resultCode == RESULT_OK &&
                (requestCode == REQUEST_VIDEO_CODE || requestCode == REQUEST_LOGIN_CODE)){
//            onRefresh();
        }
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        login();
    }

    @Override
    public void setShopCount(int count) {
        mShopCount = count;
        tvShopCount.setText(String.valueOf(count));
    }

    @Override
    public void changeShopCount(int type) {
        if(type==1){//减
            mShopCount--;
        }else if(type==2){//增加
            mShopCount++;
        }
        tvShopCount.setText(String.valueOf(mShopCount));
    }

    private void getBooksClassify(){
        loadWaitDialog();
        HttpMethod.booksClassify(this,this);
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_BOOKS_CLASSIFY) {
            ResponseList<BookTabBean> responseBean  = GsonUtil.fromJsonList(data,BookTabBean.class);
            if(responseBean!=null && responseBean.getClassify()!=null){
                mTabData.clear();
                mTabData.addAll(responseBean.getClassify());
                mBookTabAdapter.notifyDataSetChanged();
                setSelection(0);
            }
        }
    }
}
